/* eslint-disable max-len */
import React, {
  FC, useState,
} from 'react';
import { useFormatCommon, axios } from '@choerodon/master';
import { Icon, Modal, Tooltip } from 'choerodon-ui/pro';
import { omit, get, isBoolean } from 'lodash';
import { get as ChoerodonGet } from '@choerodon/inject';
import { observer } from 'mobx-react-lite';
import { inject } from 'mobx-react';

import { OverflowWrap, InfoIcon } from '@choerodon/components';
import classNames from 'classnames';
import { handlePipelineModal } from '@/routes/app-pipeline/routes/app-pipeline-edit/components/stage-edits/components/job-btn/components/job-types-panel';
import { TAB_ADVANCE_SETTINGS, TAB_FLOW_CONFIG } from '../../../../stores/CONSTANTS';
import { JOB_GROUP_TYPES } from '@/routes/app-pipeline/stores/CONSTANTS';
import ParalleLines from '../paralle-lines';

import './index.less';
import SerialLines from '../serial-lines';
import useTabData from '../../../../hooks/useTabData';
import usePipelineContext from '@/routes/app-pipeline/hooks/usePipelineContext';
import jobTypes from '@/routes/app-pipeline/routes/pipeline-manage/stores/jobsTypeMappings';
import { LARGE, MIDDLE } from '@/utils/getModalWidth';
import AddCDTask from '@/routes/app-pipeline/routes/pipeline-manage/components/PipelineCreate/components/AddCDTask';

const installItems = ChoerodonGet('configuration.devops-routes-app-pipeline-pipelineEdit:ci');
// 从天翼云判断删除是否生效
const deletePerssion = ChoerodonGet('configuration.devops-routes-app-pipeline-pipelineEdit:detele-perssion');

const createGetAppService = installItems?.create?.handleMenuClickToGetAppService;

const TooltipMap = new Map([
  ['host_deploy', '暂无此任务的主机权限'],
  ['chart_deploy', '暂无此任务的环境权限'],
  ['deployment_deploy', '暂无此任务的环境权限'],
]);

export type JobProps = {
  id:string
  name:string
  jobIndex:number
  showLines:boolean
  groupType: keyof typeof JOB_GROUP_TYPES // job的分组类型
  linesType: 'paralle' | 'serial'
  handleJobDeleteCallback: (jobIndex:number)=>void
  handleJobEditCallback:(jobIndex:number, jobData:Record<string, any>)=>boolean
} & Record<string, any>

const prefixCls = 'c7ncd-pipeline-jobItem';

const JobItem:FC<JobProps> = (props) => {
  const {
    id: jobId,
    name,
    type: jobType,
    completed,
    groupType,
    linesType,
    jobIndex,
    stageIndex,
    showLines = true,

    handleJobDeleteCallback,
    handleJobEditCallback,
    edit,
    AppState,
  } = props;

  const [_data, _setData, getTabDataByKey] = useTabData();
  const { level } = usePipelineContext();

  let currentJobGroupType: any = '';

  if (JOB_GROUP_TYPES?.[groupType]) {
    currentJobGroupType = JOB_GROUP_TYPES?.[groupType];
  } else {
    currentJobGroupType = JOB_GROUP_TYPES?.[jobType];
  }

  const formatCommon = useFormatCommon();
  // const formatJob = useFormatMessage(intlPrefix);

  const linesMap:Record<string, any> = {
    paralle: <ParalleLines />,
    serial: <SerialLines />,
  };

  const isNoPermissionItem = ['host_deploy', 'chart_deploy', 'deployment_deploy'].includes(jobType) && edit === false;

  const handleJobDelete = (e:any) => {
    e?.stopPropagation();
    handleJobDeleteCallback(jobIndex);
  };

  /**
   * 编辑job的数据
   * @param {Record<string, any>} jobData
   */
  const handleEditJobData = (jobData:Record<string, any>) => handleJobEditCallback(jobIndex, jobData);

  const handleOpenEditJobModal = async () => {
    // 保存数据的时候掉用handleEditJobData 方法
    const basicInfoTabAppServiceData = level === 'project' ? getTabDataByKey('basicInfo')?.appService : {};
    let modifyData = omit({ ...props, appService: basicInfoTabAppServiceData }, ['linesType', 'showLines', 'handleJobDeleteCallback', 'handleJobEditCallback']);
    let appServiceId;
    let appServiceName;
    if (modifyData?.appService) {
      appServiceId = modifyData?.appService?.appServiceId;
      appServiceName = modifyData?.appService?.appServiceName;
    } else if (createGetAppService) {
      const {
        type: installType,
        config,
        transformResponse,
      } = createGetAppService;
      switch (installType) {
        case 'axios': {
          const basicData = getTabDataByKey('basicInfo');
          const result = await axios(config(basicData, AppState));
          if (transformResponse) {
            appServiceId = transformResponse(result)?.appServiceId;
            appServiceName = transformResponse(result)?.appServiceName;
          }
          break;
        }
        default: {
          break;
        }
      }
      modifyData = {
        ...modifyData,
        appService: {
          appServiceId,
          appServiceName,
        },
      };
    }
    const type = modifyData?.type;
    // if (type.includes('cd')) {
    //   let flag = true;
    //   if (isNoPermissionItem) {
    //     flag = false;
    //   }
    //   if (flag) {
    //     const originData = getTabDataByKey(TAB_FLOW_CONFIG);
    //     Modal.open({
    //       key: Modal.key(),
    //       title: (
    //         <p>
    //           添加
    //           {/* @ts-ignore */}
    //           {jobTypes[type]}
    //         </p>
    //       ),
    //       style: {
    //         width: MIDDLE,
    //       },
    //       maskClosable: false,
    //       children: (
    //         <AddCDTask
    //           stageData={getTabDataByKey(TAB_FLOW_CONFIG)}
    //           jobDetail={modifyData}
    //           appServiceName={appServiceName}
    //           appServiceId={appServiceId}
    //           random={Math.random()}
    //           handleOk={handleEditJobData}
    //           taskType={type}
    //           jobIndex={jobIndex}
    //           stageIndex={stageIndex}
    //         />
    //       ),
    //       onCancel: () => {
    //         _setData(originData);
    //       },
    //       drawer: true,
    //       okText: '添加',
    //     });
    //   }
    // } else {
    handlePipelineModal({
      data: modifyData,
      callback: handleEditJobData,
      advancedData: getTabDataByKey(TAB_ADVANCE_SETTINGS),
      level,
      extraProps: {
        stageData: getTabDataByKey(TAB_FLOW_CONFIG),
        jobIndex,
        stageIndex,
      },
    });
    // }
  };

  const jobContentCls = classNames(`${prefixCls}-content`, {
    [`${prefixCls}-content-notComplete`]: isBoolean(completed) && !completed,
  });
  return (
    <Tooltip placement="right" title={isNoPermissionItem ? TooltipMap.get(jobType) : ''}>
      <div className={prefixCls}>
        {showLines && linesMap[linesType]}
        <div
          className={jobContentCls}
          role="none"
          onClick={() => {
            if (!isNoPermissionItem) {
              handleOpenEditJobModal();
            }
          }}
          style={{
            cursor: isNoPermissionItem ? 'not-allowed' : 'pointer',
          }}
        >
          <Tooltip title={get(currentJobGroupType, 'name')}>
            <Icon className={`${`${prefixCls}`}-icon`} type={get(currentJobGroupType, 'icon')} />
          </Tooltip>
          <OverflowWrap className={`${prefixCls}-name`} width={120}>
            {name}
          </OverflowWrap>
          <div className={`${prefixCls}-iconGroups`}>
            {isBoolean(completed) && !completed && (
              <InfoIcon
                className={`${prefixCls}-iconGroups-notComplete`}
              />
            )}
            <Icon
              onClick={deletePerssion && deletePerssion?.getDisabled(isNoPermissionItem) === true ? () => {} : handleJobDelete}
              type="delete_black-o"
              className={`${prefixCls}-iconGroups-delete`}
              style={{ cursor: deletePerssion && deletePerssion?.getDisabled(isNoPermissionItem) === true ? 'not-allowed' : 'pointer' }}
            />
          </div>
        </div>
      </div>
    </Tooltip>
  );
};

export default inject('AppState')(observer(JobItem));
